import Taro, { Component, Config } from '@tarojs/taro'
import {Image, Input, Slider, View} from '@tarojs/components'
import {SDBody, SDLoading} from 'sudao-ui'
import SDUtils from 'sudao-utils'

import './index.less'

import PlayIcon from '../../../images/ic_play.png'
import VoiceIcon from '../../../images/ic_voice.png'
import EmptyIcon from '../../../images/ic_nothing_search.png'
import CommonEmptyView from "../../../comps/empty-view";

type PageState = {
  keywords: string,
  mainIsLoading: boolean,
  hasData: boolean,
  hasMore: boolean,
  loading: boolean,
  hideLoading: boolean,
  dataList: any[],
}

export default class DiscoverResultPage extends Component<{}, PageState> {

  constructor () {
    super()
    this.state = {
      mainIsLoading: true,
      keywords: '',
      hasData: true,
      hasMore: true,
      loading: false,
      hideLoading: false,
      dataList: []
    }
  }

  config: Config = {
    navigationBarTitleText: '搜索结果',
    enablePullDownRefresh: true
  }

  keywords: string = ''
  code: string = ''

  articleRequestTask: any | undefined = undefined


  componentDidMount () {
    this.keywords = (this.$router.params || {}).keywords || ''
    this.code = (this.$router.params || {}).code || ''
    this.execSearch(this.keywords, this.code)
  }

  render () {
    const { mainIsLoading, loading, hasMore, hasData, hideLoading, dataList, keywords } = this.state

    return (
      <SDBody sd-class='container' loading={mainIsLoading}>
        <View className="search-content border-bottom_1px">
          <View className="search-outer">
            <Input className="search-input" value={keywords} confirmType='search' placeholder='请输入关键字' onInput={this.onInputValueChange} onConfirm={this.onSearch} />
          </View>
        </View>
        <View style='height: 128rpx;'></View>

        <View className="main-list">
          {
            dataList.map((item, index) => {
              return item.articleType == 'TEXT' ? (
                <View className="cell-item" key={index} onClick={this.gotoDiscoverDetail.bind(this, index)}>
                  <View className="cell-title">{item.title}</View>
                  <View className="cell-sub-title">{SDUtils.formatDate(item.createTime || 0, 'yyyy-MM-dd HH:mm')}</View>
                  <View className="cell-content">{ item.content }</View>
                  {
                    item.picList.length > 0 ? <View className={`cell-pic_list ${item.picList.length == 4 ? 'cell-pic_list_4' : ''}`}>
                      {
                        item.picList.map((innerItem, innerIndex) => {
                          return (
                            <View className="cell-pic_item" key={innerIndex} onClick={this.previewImage.bind(this, index, innerIndex)}>
                              <Image className="cell-pic_img" src={innerItem.content} mode='aspectFill' lazyLoad />
                            </View>
                          )
                        })
                      }
                    </View> : null
                  }
                </View>
              ) : item.articleType == 'AUDIO' ? (
                <View className="cell-item" key={index} onClick={this.gotoDiscoverDetail.bind(this, index)}>
                  <View className="cell-title">{item.title}</View>
                  <View className="cell-sub-title">2018-09-04 15:30</View>
                  <View className="cell-content">{item.content}</View>
                  <View className='cell-pic_list'>
                    <View className="audio-item">
                      <Image className="audio-left" src={VoiceIcon} />
                      <View className="audio-right">
                        <View className="audio-title">品牌化运营、推广、优化</View>
                        <Slider className="audio-slider" value={2} step={0.01} min={0} max={100} blockSize={7}
                                backgroundColor='#E2E2E2' activeColor='#934900' disabled />
                        <View className="audio-bottom">
                          <View className="audio-bottom_item">00:00</View>
                          <View className="audio-bottom_item">{SDUtils.formatDuration(item.audioTime)}</View>
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              ) : (
                <View className="cell-item" key={index} onClick={this.gotoDiscoverDetail.bind(this, index)}>
                  <View className="cell-title">{item.title}</View>
                  <View className="cell-sub-title">2018-09-04 15:30</View>
                  <View className="cell-content">{item.content}</View>
                  <View className='cell-pic_list'>
                    <View className="video-item">
                      <Image className="video-poster" src={item.videoCoverImage} />
                      <View className="inner-item">
                        <Image className="play-icon" src={PlayIcon} />
                      </View>
                    </View>
                  </View>
                </View>
              )
            })
          }
        </View>


        <SDLoading loading={loading} hasData={hasData} hasMore={hasMore} hideLoading={hideLoading}>
          <CommonEmptyView title='抱歉，没有搜索到相关文章' icon={EmptyIcon} mainTop={90} titleColor='#666' />
        </SDLoading>
      </SDBody>
    )
  }

  onInputValueChange = e => {
    this.keywords = e.detail.value
  }

  execSearch = async (keywords, code) => {
    this.keywords = keywords
    this.code = code
    this.fetchData(0, true)
  }

  onSearch = () => {
    this.execSearch(this.keywords, this.code)
  }

  onPullDownRefresh () {
    this.fetchData(0,false)
  }

  onReachBottom () {
    const { dataList } = this.state
    this.fetchData(dataList.length)
  }

  fetchData = async (offset: number = 0, setEmpty: boolean = true) => {
    let { loading, hasMore, hasData, dataList } = this.state
    if (loading || (offset > 0 && !hasMore)) { return }
    const limit = 20
    if (offset == 0) {
      dataList = []
    }
    const pageData: object = {
      loading: true,
      hasData: true,
      hasMore: true,
      hideLoading: dataList.length < limit,
      keywords: this.keywords
    }
    if (setEmpty) {
      // @ts-ignore
      pageData.dataList = dataList
    }
    await this.setState({
      ...pageData
    })

    try {
      this.articleRequestTask = SDUtils.getAbortToken()
      const result = await SDUtils.doGet('/content/wxmini/article/discover', {
        offset: offset,
        limit: 20,
        groupCode: this.code,
        title: this.keywords
      }, this.articleRequestTask) || {}
      let items = result.items || []
      items.map(item => {
        item.picList = (item.articleContent || []).filter(innerItem => innerItem.type == 'IMAGE')
        item.content = ((item.articleContent || []).find(innerItem => innerItem.type == 'TEXT') || {}).content || ''
        return item
      })
      dataList = dataList.concat(items)
      hasData = result.total > 0
      hasMore = result.total > dataList.length
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      setTimeout(() => {
        Taro.stopPullDownRefresh()
        this.setState({
          mainIsLoading: false,
          loading: false,
          hasMore: hasMore,
          hasData: hasData,
          dataList: dataList,
          hideLoading: false
        })
      }, 1000)
    }
  }

  // 取消之前网络请求
  cancelPreRequest = async () => {
    this.articleRequestTask && this.articleRequestTask.abort()
  }

  previewImage = (index, innerIndex, e) => {
    e.stopPropagation()
    const { dataList } = this.state
    let dataItem = dataList[index]
    let picList = dataItem.picList
    let picItem = picList[innerIndex]

    Taro.previewImage({
      urls: picList.map(item => {
        return item.content
      }),
      current: picItem.content
    })
  }

  gotoDiscoverDetail = (index) => {
    const { dataList } = this.state
    let dataItem = dataList[index]
    SDUtils.jumpTo('/pages/discover/detail/index', {
      articleId: dataItem.articleId
    })
  }

}
